
import json
import tkinter as tk
from datetime import datetime
import requests
import xlwt
import random
from collections import Counter

# 0.获取实时时间
def get_time():
    now = datetime.now()
    today_str = now.strftime('%Y-%m-%d')
    return today_str

# 清除内容
def clear_text_widget():
    text_widget.delete("1.0", "end")

# 1.爬取开奖数据
def get_history_datas():
    if entry_widget.get():
        pz = entry_widget.get()
    else:
        pz = '100'
    url = f'http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&pageNo=1&pageSize={pz}&systemType=PC'
    headers = {
        'Host': 'www.cwl.gov.cn',
        'Referer': 'http://www.cwl.gov.cn/c/2023/01/17/527544.shtml',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; root64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    result = json.loads(response.text).get('result')
    data_dict = {}
    for res in result:
        data_dict[res['code']] = res['red'] + "," + res['blue']
    return data_dict

# 2.保存ex数据
def savedatas_to_ex():
    clear_text_widget()
    data_dict = get_history_datas()
    today = get_time()
    excel_path = f'{today}历史数据.xls'
    wb = xlwt.Workbook()
    she = wb.add_sheet("彩票")
    al = xlwt.Alignment()
    al.horz = 0x02
    al.vert = 0x01
    borders = xlwt.Borders()
    borders.left = xlwt.Borders.THIN
    borders.right = xlwt.Borders.THIN
    borders.top = xlwt.Borders.THIN
    borders.bottom = xlwt.Borders.THIN
    pattern = xlwt.Pattern()
    pattern.pattern = xlwt.Pattern.SOLID_PATTERN
    pattern.pattern_fore_colour = 27
    style0 = xlwt.XFStyle()
    style0.alignment = al
    font0 = xlwt.Font()
    font0.bold = True
    font0.colour_index = 0
    style0.font = font0
    style0.borders = borders
    style0.pattern = pattern
    style01 = xlwt.XFStyle()
    style01.alignment = al
    font01 = xlwt.Font()
    font01.bold = True
    font01.colour_index = 2
    style01.font = font01
    style01.borders = borders
    style01.pattern = pattern
    style02 = xlwt.XFStyle()
    style02.alignment = al
    font02 = xlwt.Font()
    font02.bold = True
    font02.colour_index = 12
    style02.font = font02
    style02.borders = borders
    style02.pattern = pattern
    style = xlwt.XFStyle()
    style.alignment = al
    font = xlwt.Font()
    font.colour_index = 12
    style.font = font
    style.borders = borders
    style1 = xlwt.XFStyle()
    font1 = xlwt.Font()
    font1.colour_index = 2
    style1.font = font1
    style1.borders = borders
    she.write(0, 0, "期数\\彩票", style0)
    for i in range(1, 34):
        she.write(0, i, i, style01)
    for j in range(1, 17):
        she.write(0, j + 33, j, style02)
    for k in range(1, 50):
        she.col(k).width = 256 * 3
    i = 1
    for key, value in data_dict.items():
        she.write(i, 0, key, style0)
        values = value.split(",")
        red_list = values[0:-1]
        lan = int(values[-1])
        for hong in red_list:
            she.write(i, int(hong), int(hong), style1)
        she.write(i, lan + 33, lan, style)
        i += 1
    wb.save(excel_path)
    text_widget.insert('insert', "数据已保存: " + excel_path + "\n")

# 3.打印历史双色球数据，并在前端显示
def print_history_datas():
    data_dict = get_history_datas()
    clear_text_widget()
    str_result = ""
    for key, value in data_dict.items():
        ball = " ".join(value.split(","))
        str_result += "第" + key + "期：" + ball + "\n"
    text_widget.insert('insert', str_result)

# 4.数据统计分析，并在前端显示
def analysis_datas():
    clear_text_widget()
    data_dict = get_history_datas()
    red_list = []
    blue_list = []
    for key, value in data_dict.items():
        red_ball = value.split(",")[:-1]
        red_list.extend(red_ball)
        blue_ball = value.split(",")[-1]
        blue_list.append(blue_ball)
    red_dict = Counter(red_list)
    blue_dict = Counter(blue_list)
    red_dict = sorted(red_dict.items(), key=lambda x: x[1], reverse=True)
    blue_dict = sorted(blue_dict.items(), key=lambda x: x[1], reverse=True)
    red_ball_result = f'近{entry_widget.get()}期红色球解析结果(倒序)：\n'
    blue_ball_result = f'近{entry_widget.get()}期蓝色球解析结果(倒序)：\n'
    for k, v in red_dict:
        red_ball_result += k + " 出现次数：" + str(v) + "\n"
    for k, v in blue_dict:
        blue_ball_result += k + " 出现次数：" + str(v) + "\n"
    result = red_ball_result + blue_ball_result
    text_widget.insert('insert', result)

# 5.预测下次双色球开奖号码
def predict_next_numbers():
    clear_text_widget()
    red_balls = random.sample(range(1, 34), 6)
    blue_ball = random.randint(1, 16)
    red_balls_str = ' '.join(map(str, sorted(red_balls)))
    prediction = f"预测下次双色球开奖号码：\n红球：{red_balls_str}\n蓝球：{blue_ball}\n"
    text_widget.insert('insert', prediction)

# 6.主函数
if __name__ == '__main__':
    root = tk.Tk()
    root.title('福彩双色球预测分析工具')
    root.geometry('800x600')

    entry_var = tk.StringVar()
    entry_widget = tk.Entry(root, width=22, bg='yellow', bd=3, textvariable=entry_var)
    entry_widget.grid(row=0, column=0, padx=10, pady=10)
    tk.Label(root, text='历史期数(期):').grid(row=0, column=1, padx=10, pady=10)
    tk.Label(root, text="注：只可填入数字,填10表示前10期数据,不填默认为100").grid(row=1, column=0, columnspan=2, padx=10, pady=5)

    text_widget = tk.Text(root, height=20, width=80)
    text_widget.grid(row=2, column=0, columnspan=2, padx=10, pady=10)

    xz_button = tk.Button(root, text='下载数据', command=print_history_datas)
    xz_button.grid(row=3, column=0, padx=10, pady=10)
    ex_button = tk.Button(root, text='生成Excel文件', command=savedatas_to_ex)
    ex_button.grid(row=3, column=1, padx=10, pady=10)
    jx_button = tk.Button(root, text="解析数据", command=analysis_datas)
    jx_button.grid(row=4, column=0, padx=10, pady=10)
    yc_button = tk.Button(root, text="预测开奖号码", command=predict_next_numbers)
    yc_button.grid(row=4, column=1, padx=10, pady=10)
    qk_button = tk.Button(root, text="清空内容", command=clear_text_widget)
    qk_button.grid(row=5, column=0, padx=10, pady=10)

    root.mainloop()
